package com.shinhye.elephantsafe.service;

import java.util.Timer;
import java.util.TimerTask;

import com.shinhye.elephantsafe.R;
import com.shinhye.elephantsafe.recevier.ESafeWidget;
import com.shinhye.elephantsafe.utils.SystemInfoUtils;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.format.Formatter;
import android.util.Log;
import android.widget.RemoteViews;

public class UpdateWidgetService extends Service {
	private String TAG = "UpdateWidgetService";
	private Timer timer;
	private TimerTask task;
	private AppWidgetManager awm;
	private LockScreenReceiver receiver;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.i(TAG, "服务开启了！");
		
		receiver = new LockScreenReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(receiver, filter);
		
		awm = AppWidgetManager.getInstance(UpdateWidgetService.this);
		startUpdateWidget();
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "服务关闭了！");
		timer.cancel();
		task.cancel();
		timer = null;
		task = null;
		
		unregisterReceiver(receiver);
		receiver = null;
	}
	
	/**
	 * A method to startup refreshing Widget UI at fixed period(5 seconds).
	 */
	public void startUpdateWidget() {
		timer = new Timer();
		task = new TimerTask() {
			@Override
			public void run() {
				Log.i(TAG, "定时任务运行了！");
				
				RemoteViews views = new RemoteViews(getPackageName(), R.layout.widget_elephantsafe);
				views.setTextViewText(R.id.tv_process_count, "正在运行的软件：" + SystemInfoUtils.getRunningProcessCount(UpdateWidgetService.this));
				views.setTextViewText(R.id.tv_process_memory, "可用内存：" + Formatter.formatFileSize(UpdateWidgetService.this, SystemInfoUtils.getAvailRAM(UpdateWidgetService.this)));
				
				ComponentName componentName = new ComponentName(UpdateWidgetService.this, ESafeWidget.class);
				awm.updateAppWidget(componentName, views);
			}
		};
		timer.schedule(task, 0, 5000);
	}
	
	/**
	 * Receiver the lock screen broadcast to start or stop widget UI refresh operation.
	 * @author ShinHye
	 *
	 */
	private class LockScreenReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
				Log.i(TAG, "收到锁屏广播了！停止Widget刷新！");
				timer.cancel();
				task.cancel();
				timer = null;
				task = null;
			} else if(Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
				Log.i(TAG, "收到锁屏广播了！开启Widget刷新！");
				startUpdateWidget();
			}
			
		}
	}

}
